package com.example.mapper;

import com.example.entity.PickupCode;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

public interface PickupCodeMapper {
    void insert(PickupCode pickupCode);

    PickupCode selectMaxCode();

    @Select("SELECT COUNT(*) FROM pickup_code WHERE trackingNumber = #{trackingNumber}")
    int countByTrackingNumber(String trackingNumber);

    @Select("SELECT * FROM pickup_code WHERE trackingNumber = #{trackingNumber} ORDER BY created_at DESC LIMIT 1")
    PickupCode selectLatestByTrackingNumber(String trackingNumber);

    @Select("SELECT * FROM pickup_code ORDER BY created_at DESC LIMIT 1")
    PickupCode selectLatestCode();

    // 回收取件码
    @Update("UPDATE pickup_code SET trackingNumber = NULL WHERE trackingNumber = #{trackingNumber}")
    void clearTrackingNumber(String trackingNumber);

    // 查询可回收的取件码（按创建时间最早）
    @Select("SELECT * FROM pickup_code WHERE trackingNumber IS NULL ORDER BY created_at ASC LIMIT 1")
    PickupCode selectRecycledCode();

    // 分配取件码给新包裹
    @Update("UPDATE pickup_code SET trackingNumber = #{trackingNumber} WHERE id = #{id}")
    void assignTrackingNumber(@Param("id") Long id, @Param("trackingNumber") String trackingNumber);

    void clearTrackingNumbers(@Param("trackingNumbers") List<String> trackingNumbers);
}
